<template>
    <div class="create-edit-modal-wrapper">
        <el-dialog :model-value="props.value" :width="dialog.width" destroy-on-close>
            <template #header>
                <div class="el-dialog__title">
                    <span>{{ dialog.title }}</span>
                    <span v-if="isDevice()" style="color: #999; font-size: 12px; margin-left: 10px">
                        注：该产品下已有设备，仅允许修改与设备通讯无关的信息！
                    </span>
                </div>
            </template>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="100px">
                <el-form-item label="产品名称" prop="productName">
                    <el-input
                        v-model="formData.productName"
                        @input="value => (formData.productName = value.trim())"
                        placeholder="请输入模型名称"
                        :disabled="isEdit()"
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="产品标签">
                    <el-tree-select
                        v-model="formData.labels"
                        :data="labelTree"
                        :props="defaultProps"
                        @visible-change="visibleChange"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        :render-after-expand="false"
                        show-checkbox
                        node-key="labelNo"
                    />
                </el-form-item>
                <el-form-item label="产品模型" prop="objectName">
                    <el-select
                        v-model="formData.objectName"
                        placeholder="请选择产品模型"
                        filterable
                        :disabled="isEdit()"
                    >
                        <el-option
                            v-for="item in productModelList"
                            :label="item.displayName"
                            :key="item.objectName"
                            :value="item.objectName"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="标识符">
                    <el-input placeholder="系统自动生成" v-model="formData.productNo" disabled />
                </el-form-item>
                <el-form-item label="节点类型" prop="productType">
                    <el-radio-group v-model="formData.productType" :disabled="isDevice()" @change="productTypeChange">
                        <el-radio v-for="(value, key) in ProductType" :key="key" :label="key">{{ value }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <template v-if="formData.productType !== 'CLOUD_GATEWAY'">
                    <el-form-item label="通讯协议" class="protocol-box" prop="protocolNo">
                        <el-select
                            v-model="formData.protocolType"
                            placeholder="请选择通讯方式"
                            @change="protocolTypeChange"
                            :disabled="isDevice()"
                        >
                            <el-option
                                v-for="item in protocolTypeList"
                                :label="item.protocolType"
                                :key="item.id"
                                :value="item.protocolType"
                            />
                        </el-select>
                        <el-select
                            v-model="formData.protocolNo"
                            placeholder="请选择具体协议"
                            :disabled="formData.protocolType && isDevice()"
                        >
                            <el-option
                                v-for="item in protocolNoList"
                                :label="item.protocolName"
                                :key="item.id"
                                :value="item.protocolNo"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="网络组件" prop="networkComponentNo" v-if="formData.protocolType === 'mqtt'">
                        <el-select
                            v-model="formData.networkComponentNo"
                            placeholder="请选择网络组件"
                            :disabled="isDevice()"
                        >
                            <el-option
                                v-for="item in netComponentList"
                                :label="item.componentName"
                                :key="item.id"
                                :value="item.componentNo"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="注册模式" prop="connectMode" v-else>
                        <el-radio-group v-model="formData.connectMode" :disabled="isDevice()">
                            <el-radio v-for="(value, key) in ConnectMode" :key="key" :label="key">{{ value }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template>
                <el-form-item label="NB-IoT平台" v-else>
                    <el-select placeholder="请选择NB-IoT平台" :disabled="isDevice()">
                        <el-option v-for="(value, key) in []" :label="value" :key="key" :value="key" />
                    </el-select>
                </el-form-item>
                <el-form-item label="超时离线" prop="timeout">
                    <el-input-number
                        v-model="formData.timeout"
                        :precision="0"
                        :min="1"
                        :max="86400"
                        style="width: 100%"
                        align="left"
                        controls-position="right"
                        placeholder="请输入超时离线"
                    >
                        <template #suffix>
                            <span>秒</span>
                        </template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="描述" style="width: 100%; margin-left: 0">
                    <el-input
                        v-model="formData.productDesc"
                        type="textarea"
                        maxlength="200"
                        show-word-limit
                        placeholder="请输入描述"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { IoTProductService, IoTProtocolService, IoTNetComponentService, runLabelService } from '@great/services';
import { reactive, ref } from 'vue';
import { ProductType, ConnectMode } from '@/utils/constant';
import { useRouter } from 'vue-router';
import type { PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';

interface IProps extends PopupBoxProps {
    row?: Record<string, any>;
    callBack?: () => Promise<void>;
}
const props = defineProps<IProps>();
const router = useRouter();

interface Dialog {
    title: string;
    width: number;
    detail?: Record<string, any>;
}
const dialog = reactive<Dialog>({
    title: '新建产品',
    width: 900,
    detail: undefined
});
const defaultProps = {
    children: 'childLabel',
    label: 'labelName',
    value: 'labelNo'
};
const formData = reactive<Record<string, any>>({
    productName: '',
    productDesc: '',
    productType: 'DIRECT',
    protocolType: '',
    productNo: '',
    protocolNo: null,
    connectMode: 'ACTIVE',
    objectName: '',
    networkComponentNo: '',
    timeout: null,
    id: null,
    labels: []
});
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<FormRules<any>>({
    productName: [{ required: true, message: '请输入产品名称', trigger: ['blur', 'change'] }],
    objectName: [{ required: true, message: '请选择产品模型', trigger: ['blur', 'change'] }],
    productType: [{ required: true, message: '请选择节点类型', trigger: ['blur', 'change'] }],
    protocolNo: [{ required: true, message: '请选择通讯协议', trigger: ['blur', 'change'] }],
    connectMode: [{ required: true, message: '请选择注册模式', trigger: ['blur', 'change'] }],
    networkComponentNo: [{ required: true, message: '请选择网络组件', trigger: ['blur', 'change'] }],
    timeout: [{ required: true, message: '请输入超时离线', trigger: ['blur', 'change'] }]
});
const productModelList = ref<Array<Record<string, string>>>([]);
const protocolTypeList = ref<Array<Record<string, string>>>([]);
const protocolNoList = ref<Array<Record<string, string>>>([]);
const netComponentList = ref<Array<Record<string, string>>>([]);
const labelTree = ref();

const productTypeChange = () => {
    formData.protocolType = '';
    formData.protocolNo = '';
    getProtocolTypeList();
};

// 获取产品模型列表
const getProductModel = async () => {
    const res = await IoTProductService.getProductModel({
        showAttribute: false,
        showChildren: false,
        isActivate: 1,
        isComponent: false,
        usageType: 'THING',
        modifierTypes: 'SINGLE,EXTENDED'
    });
    productModelList.value = res.data;
};

// 获取通讯方式列表
const getProtocolTypeList = async () => {
    const res = await IoTProtocolService.getProtocolTypeList({
        productType: formData.productType
    });
    protocolTypeList.value = res.data;
};
// 获取具体协议列表
const getProtocolNoList = async () => {
    const res = await IoTProtocolService.getProtocolPublicList({ protocolType: formData.protocolType });
    protocolNoList.value = res.data;
};
// 获取网络组件列表
const getNetComponentList = async () => {
    if (formData.protocolType === 'mqtt') {
        if (netComponentList.value.length === 0) {
            const res = await IoTNetComponentService.getNetComponentList();
            netComponentList.value = res.data;
        }
    } else {
        formData.networkComponentNo = '';
    }
};
const getDefaultTimeout = async () => {
    const res = await IoTProductService.getDefaultTimeout();
    if (res.data || res.data == 0) {
        formData.timeout = +res.data;
    }
};
// 通讯方式选择
const protocolTypeChange = () => {
    formData.protocolNo = null;
    getProtocolNoList();
    getNetComponentList();
};
// 是否为编辑
const isEdit = (par?: boolean): boolean => {
    if (par === undefined) {
        return dialog.title.includes('修改');
    } else {
        return dialog.title.includes('修改') && par;
    }
};
// 是否具有设备
const isDevice = (): boolean => {
    return props.row && props.row.deviceCount ? true : false;
};
// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return IoTProductService[isEdit() ? 'editProduct' : 'createProduct'](formData);
    },
    {
        manual: true,
        onSuccess(res) {
            if (isEdit()) {
                ElNotification({
                    title: '修改成功！',
                    type: 'success'
                });
            } else {
                ElMessageBox.confirm('请继续为产品进行任务设置！', '创建成功', {
                    confirmButtonText: '继续',
                    cancelButtonText: '完成',
                    type: 'success'
                })
                    .then(() => {
                        router.push({
                            name: 'IoT-product-detail',
                            params: {
                                id: res.data
                            }
                        });
                    })
                    .catch(() => {});
            }
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    ruleFormRef.value?.validate(valid => {
        if (valid) {
            ElMessageBox.confirm('请确认产品名称和产品模型，保存后将不可修改！', '提示', {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'success'
            })
                .then(() => {
                    run();
                })
                .catch(() => {});
        }
    });
};

// 标签下拉框显隐
const visibleChange = (visible: boolean) => {
    if (visible) getLabelTree();
};
// 获取标签
const getLabelTree = async () => {
    if (labelTree.value && labelTree.value.length > 0) return;
    const res = await runLabelService.getLabelTree({ labelTypeNo: 'labelType-producctLabel' });
    labelTree.value = res.data;
};

//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};

// 打开弹框
const openDialog = () => {
    if (props.row) {
        dialog.title = '修改产品';
        dialog.detail = JSON.parse(JSON.stringify(props.row));
        formData.id = props.row.id;
        Object.keys(formData).forEach(key => {
            formData[key] = props.row?.[key];
        });
        getLabelTree();
        // 节点类型 != '云网关设备'
        if (formData.productType !== 'CLOUD_GATEWAY') {
            getProtocolTypeList();
            getProtocolNoList();
            getNetComponentList();
        }
    } else {
        delete formData.id;
        getProtocolTypeList();
        getDefaultTimeout();
    }
};

const init = () => {
    getProductModel();
    openDialog();
};
init();
</script>
<style scoped lang="scss">
.create-edit-modal-wrapper {
    .el-form {
        display: flex;
        flex-wrap: wrap;
        .el-form-item {
            width: calc((100% - 10px) / 2);
        }
        .el-form-item:nth-child(even) {
            margin-left: 10px;
        }
        :deep(.protocol-box) {
            .el-form-item__content {
                display: flex;
                .el-select {
                    flex: 1;
                }
                .el-select + .el-select {
                    margin-left: 10px;
                }
            }
        }
    }
}
</style>
